<template>
  <div>
    <a-card>
      <div class="table-operator">
        <a-button type="primary" @click="linkTo(1, 1)" slot="extra">
          <a-icon type="plus" />新增组织
        </a-button>
      </div>

      <a-table
        rowKey="id"
        defaultExpandAllRows
        :key="tableKey"
        :columns="columns"
        :dataSource="pageData.records"
        :loading="pageData.tableLoading"
        :pagination="false"
      >
        <span slot="createTime" slot-scope="text">
          {{ text | moment }}
        </span>
        <span slot="action" slot-scope="text, record">
          <a @click.prevent="() => linkTo(0, record.id, record.majorName)">修改</a>
          <a-divider type="vertical" />
          <a-popconfirm title="确定删除吗?" @confirm="() => batchDelete(record.id)">
            <a href="javascript:;" style="color:#ff4d4f">删除</a>
          </a-popconfirm>
        </span>
      </a-table>
    </a-card>

    <!-- 点击编辑按钮出现的弹框 -->
    <a-drawer
      :title="infoDialog.title"
      :visible.sync="infoDialog.show"
      width="600px"
      center
      @close="infoDialog.show = false"
    >
      <Info :current-info="infoDialog" :orgOptions="pageData.records" @emitToParent="getChildValue" />
    </a-drawer>
  </div>
</template>

<script>
import { getOrgTree, deleteOrgInfo } from '@/api/system'
import { listToTree } from '@/utils/common'

const columns = [
  {
    title: '名称',
    dataIndex: 'majorName'
  },
  {
    title: '描述',
    dataIndex: 'narrate'
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    scopedSlots: { customRender: 'createTime' }
  },
  {
    title: '操作',
    dataIndex: 'action',
    scopedSlots: { customRender: 'action' }
  }
]

export default {
  components: {
    Info: () => import('./info')
  },
  data () {
    return {
      tableKey: 0,
      columns, // 表格列数据项
      pageData: { // 表格数据列表
        tableLoading: false,
        records: []
      },
      infoDialog: { // 对话框
        show: false,
        title: '新增组织',
        type: 'add',
        id: ''
      }
    }
  },
  created () {
    // this.getList()
  },
  methods: {
    // 获取子组件的值
    getChildValue (val) {
      this.infoDialog.show = false
      val && this.getList()
    },
    // 查询列表
    getList () {
      this.pageData.tableLoading = true
      getOrgTree().then(res => {
        const orgList = []
        listToTree(res.content || [], orgList, 1)
        this.pageData.records = orgList
        this.tableKey++
      }).finally(res => {
        this.pageData.tableLoading = false
      })
    },
    // 跳转详情页
    linkTo (isAdd, id, name) {
      this.infoDialog = {
        show: true,
        isAdd,
        title: isAdd ? '新增组织' : ('修改组织：' + name),
        id: isAdd ? id + Math.random() : id
      }
    },
    // 删除
    batchDelete (id) {
      deleteOrgInfo({ id: id }).then(response => {
        this.$message.success('删除成功！')
        this.getList()
      })
    }
  }
}
</script>
